<?php
namespace app\api\controller;

use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use support\Request;

// 引入 UUID 生成库

class ImageController extends BaseClientController
{

    private $accessKeyId;
    private $accessKeySecret;
    private $region;
    private $bucket;
    private $endpoint;
    private $ossClient;

    public function __construct()
    {
        parent::__construct();
        // 从配置文件读取OSS信息
        $this->accessKeyId     = config('oss.access_key_id');
        $this->accessKeySecret = config('oss.access_key_secret');
        $this->region          = config('oss.region');
        $this->bucket          = config('oss.bucket');
        $this->endpoint        = config('oss.endpoint');

        $provider = new StaticCredentialsProvider($this->accessKeyId, $this->accessKeySecret);

        // 初始化OSS客户端
        try {
            $this->ossClient = new OssClient(
                [
                    'provider' => $provider,
                    'region'   => $this->region,
                    'endpoint' => $this->endpoint,
                ]
            );
        } catch (OssException $e) {
            throw new \RuntimeException('OSS初始化失败: ' . $e->getMessage());
        }
    }

    public function upload(Request $request)
    {
        $file = $request->file('image');
        if (! $file) {
            throw new BusinessException('请选择要上传的图片');
        }
        // 使用 getOriginalName 方法获取原始文件名，再用 pathinfo 函数获取文件扩展名
        $ext = $file->getUploadExtension();
        if (! in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
            throw new \RuntimeException('不支持的图片格式');
        }
        // 保存临时文件
        $tempPath = $file->getRealPath();
        if (! file_exists($tempPath)) {
            throw new \RuntimeException('文件不存在');
        }
        // 生成唯一文件名
        $fileName = date('Ymd') . uniqid() . '.' . $ext;
        // 上传文件到OSS
        $this->ossClient->uploadFile(
            $this->bucket,
            $fileName,
            $tempPath
        );
        // 生成访问URL
        $url = 'https://' . $this->bucket . '.' . $this->region . ".aliyuncs.com" . '/' . $fileName;

        return $this->success([
            'url' => $url,
        ]);
    }
}
